package com.lablzh.gdxy.service.impl;

import com.lablzh.gdxy.component.DynamicOperateExcelUtils;
import com.lablzh.gdxy.component.UserDetailsUtil;
import com.lablzh.gdxy.entity.*;
import com.lablzh.gdxy.entity.admin.Parameter;
import com.lablzh.gdxy.entity.assistant.Assistant;
import com.lablzh.gdxy.entity.assistant.AssistantApply;
import com.lablzh.gdxy.entity.assistant.StudentAssistant;
import com.lablzh.gdxy.repository.*;
import com.lablzh.gdxy.repository.admin.ParameterRepository;
import com.lablzh.gdxy.repository.assistant.AssistantApplyRepository;
import com.lablzh.gdxy.repository.assistant.AssistantRepository;
import com.lablzh.gdxy.repository.assistant.StudentAssistantRepository;
import com.lablzh.gdxy.service.AssistantService;
import com.lablzh.gdxy.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AssistantServiceImpl implements AssistantService {
    private static final String BASEPATH = "./resources/static/";
    @Autowired
    private UserDetailsUtil userDetailsUtil;
    @Autowired
    private StudentRepositoty studentRepositoty;

    @Autowired
    private AssistantRepository assistantRepository;
    @Autowired
    private AssistantApplyRepository assistantApplyRepository;
    @Autowired
    private StudentAssistantRepository studentAssistantRepository;
    @Autowired
    private ParameterRepository parameterRepository;
    @Autowired
    private FileService fileService;
    @Autowired
    private TeacherRepository teacherRepository;

    @Override
    public String createTeam(Assistant assistant) {
//        if(assistantRepository.findByName(assistant.getName())!=null) {
//            return "该助教助研项目已存在！";
//        }
        Parameter parameter = parameterRepository.findByCollegeAndGradeAndType(assistant.getCollege(), assistant.getGrade(), "助教助研");
        if (parameter == null) {
            return "教务员未设置初始互选参数！";
        }
        //初始化
        assistant.setApplyed(0);
        assistant.setRecv(0);
        assistant.setTaskStart(parameter.getTaskStart());
        assistant.setTaskDdl(parameter.getTaskDdl());
        assistant.setStuChooseStart(parameter.getStuChooseStart());
        assistant.setStuChooseDdl(parameter.getStuChooseDdl());
        assistant.setTeaChooseStart(parameter.getTeaChooseStart());
        assistant.setTeaChooseDdl(parameter.getTeaChooseDdl());
        assistant.setMaxApply(parameter.getMaxApply());
        assistant.setMaxRecv(parameter.getMaxRecv());
        if (assistantRepository.save(assistant) != null) {
            return "创建成功！";
        } else {
            return "创建失败！";
        }
    }

    @Override
    public String updateTeam(Assistant assistant) {
        assistantRepository.save(assistant);
        return "修改成功！";
    }

    @Override
    public List<Assistant> getAllTeam() {
        return assistantRepository.findAll(Sort.by(Sort.Direction.DESC, "id"));
    }

    @Override
    public Assistant getOneTeam(Integer id) {
        return assistantRepository.findById(id).orElse(null);
    }

    @Override
    public String undo(Integer id) {
        AssistantApply assistantApply = assistantApplyRepository.findById(id).orElse(null);
        if(!userDetailsUtil.getUserDetails().equals(assistantApply.getStudentUsername()))
        {
            return "你无权撤销！";
        }
        if (assistantApply == null) {
            return "不存在该申请！";
        }
        if ("已通过".equals(assistantApply.getStatus())) {
            return "该申请已通过，不能取消！";
        }
        int applyed=assistantRepository.findById(assistantApply.getProjectID()).orElse(null).getApplyed();
        if("未审".equals(assistantApply.getStatus()))
        {
            applyed--;
        }
        assistantApplyRepository.deleteById(id);
        assistantRepository.updateApplyedById(assistantApply.getProjectID(),
                applyed);
        return "删除成功！";
    }

    @Override
    public String deleteTeam(Integer id) {
        assistantApplyRepository.deleteByProjectID(id);
        studentAssistantRepository.deleteByProjectID(id);
        assistantRepository.deleteById(id);
        return "删除成功！";
    }

    @Override
    public String apply(Integer id) {
        String username = userDetailsUtil.getUserDetails();
        Student student = studentRepositoty.findAllByStID(username);
        Assistant assistant = assistantRepository.findById(id).orElse(null);
        //判断
        LocalDate now = LocalDate.now();
        assert assistant != null;
        if (assistant.getMaxApply() <= assistant.getApplyed()) {
            return "申请人数已达到上限！";
        }
        if (now.isBefore(assistant.getStuChooseStart())) {
            return "学生选择未开始！";
        }
        if (now.isAfter(assistant.getStuChooseDdl())) {
            return "学生选择已结束！";
        }
        if (assistantApplyRepository.findByStudentUsernameAndProjectID(student.getStID(), id) != null) {
            return "请不要重复申请!";
        }
   //     List<AssistantApply> allByStudentUsername = assistantApplyRepository.findAllByStudentUsername(student.getStID());
//        for (AssistantApply assistantApply : allByStudentUsername) {
//            if("已通过".equals(assistantApply.getStatus())){
//                Assistant assistant1 = assistantRepository.findById(assistantApply.getProjectID()).orElse(null);
//                if(assistant1.getCategory()!=null&&assistant1.getCategory().equals(assistant.getCategory())){
//                    return "当前季度，你已成为其他课程助教";
//                }
//            }
//        }
        //已申请+1
        assistantRepository.updateApplyedById(id, assistant.getApplyed() + 1);
        //初始化
        AssistantApply assistantApply = new AssistantApply();
        assistantApply.setProjectID(id);
        assistantApply.setCollege(assistant.getCollege());
        assistantApply.setStudentUsername(student.getStID());
        assistantApply.setStudentName(student.getName());
        assistantApply.setTeacher(assistant.getTeacherUsername());
        assistantApply.setProjectName(assistant.getName());
        assistantApply.setStatus("未审");
        if (assistantApplyRepository.save(assistantApply) != null) {
            return "申请成功！";
        }
        return "申请失败！";
    }

    @Override
    public List<AssistantApply> applyTeacher() {
        String username = userDetailsUtil.getUserDetails();
        return assistantApplyRepository.findAllByTeacher(username);
    }

    @Override
    public List<AssistantApply> applyStudent() {
        String username = userDetailsUtil.getUserDetails();
        return assistantApplyRepository.findAllByStudentUsername(username);
    }

    @Override
    public List<AssistantApply> applyTeam(Integer id) {
        return assistantApplyRepository.findAllByProjectID(id);
    }

    @Override
    public String confirm(Integer id) {
        LocalDate now = LocalDate.now();
        AssistantApply assistantApply = assistantApplyRepository.findById(id).orElse(null);
        assert assistantApply != null;
        Assistant assistant = assistantRepository.findById(assistantApply.getProjectID()).orElse(null);
        Student student = studentRepositoty.findAllByStID(assistantApply.getStudentUsername());
        //判断
        assert assistant != null;
        if (assistant.getMaxRecv() <= assistant.getRecv()) {
            return "确认人数已达到上限!";
        }
        if (now.isBefore(assistant.getTeaChooseStart())) {
            return "教师选择未开始!";
        }
        if (now.isAfter(assistant.getTeaChooseDdl())) {
            return "教师选择已结束！";
        }
        if ("已通过".equals(assistantApply.getStatus())) {
            return "已审核过!";
        }

        if (assistantApplyRepository.updateStatusById(id, "已通过") == 0) {
            return "修改失败！";
        }
   //     List<AssistantApply> allByStudentUsername = assistantApplyRepository.findAllByStudentUsername(student.getStID());
//        for (AssistantApply apply : allByStudentUsername) {
//            if(apply.getId().equals(id)) {
//                continue;
//            }
//            Assistant assistant1 = assistantRepository.findById(assistantApply.getProjectID()).orElse(null);
//            if(assistant1.getCategory()!=null&&assistant1.getCategory().equals(assistant.getCategory())){
//                assistantApplyRepository.deleteById(apply.getId());
//            }
//        }
        assistant.setRecv(assistant.getRecv() + 1);
        assistantRepository.save(assistant);
        //初始化
        StudentAssistant studentAssistant = new StudentAssistant();
        studentAssistant.setProjectID(assistantApply.getProjectID());
        studentAssistant.setProjectName(assistant.getName());
        studentAssistant.setStudentUsername(assistantApply.getStudentUsername());
        studentAssistant.setStudentName(student.getName());
        studentAssistant.setTeacherUsername(assistant.getTeacherUsername());
        studentAssistant.setCollege(assistant.getCollege());
        studentAssistant.setMajor(student.getMajor());
        studentAssistant.setClasses(student.getClasses());
        studentAssistant.setGrade(assistant.getGrade());
        studentAssistant.setCategory(assistant.getCategory());
        studentAssistantRepository.save(studentAssistant);
        return "保存成功！";
    }

    @Override
    public String refuse(Integer id) {
        AssistantApply assistantApply = assistantApplyRepository.findById(id).orElse(null);
        assert assistantApply != null;
        if ("未通过".equals(assistantApply.getStatus())) {
            return "请不要重复拒绝！";
        }
        if (assistantApplyRepository.updateStatusById(id, "未通过") == 0) {
            return "修改失败！";
        }

        Assistant assistant=assistantRepository.findById(assistantApply.getProjectID()).orElse(null);
        assert assistant != null;
        assistantRepository.updateApplyedById(assistant.getId(),assistant.getApplyed()-1);
//        assistantRepository.updateRecvById(assistant.getId(),assistant.getRecv()-1);
//        studentAssistantRepository.deleteByProjectIDAndStudentUsername(assistantApply.getProjectID(),assistantApply.getStudentUsername());
        return "修改成功！";
    }

    @Override
    public List<StudentAssistant> queryPerformance(StudentAssistant studentAssistant) {
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("college", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("major", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("grade", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("classes", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("studentName", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("studentUsername", ExampleMatcher.GenericPropertyMatchers.contains());

        Example<StudentAssistant> example = Example.of(studentAssistant, matcher);
        List<StudentAssistant> ls = studentAssistantRepository.findAll(example);
        return ls;
    }

    @Override
    public void getStudentChoose(String type, String college, String major, String grade, String category,
                                 HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        DynamicOperateExcelUtils dynamicOperateExcelUtils = new DynamicOperateExcelUtils(BASEPATH + "助教助研/" + "学生选题情况统计报表模板.xlsx");
        Map<String, String> typeMap = new HashMap<>();
        typeMap.put("已确定课题学生名单", "已通过");
        typeMap.put("未确定课题学生名单", "未审");
        List<Map<String, Object>> datas = new ArrayList<>();
        List<Assistant> assistants = null;
        if ("".equals(major)) {
            assistants = assistantRepository.findAllByCollegeAndGradeAndCategory(college, grade, category);
        } else {
            assistants = assistantRepository.findAllByCollegeAndMajorAndGradeAndCategory(college, major, grade, category);
        }
        for (Assistant assistant : assistants) {
            String projectName = assistant.getName();
            List<AssistantApply> assistantApplies = assistantApplyRepository.findAllByProjectIDAndStatus(assistant.getId(), typeMap.get(type));
            for (AssistantApply assistantApply : assistantApplies) {
                Student student = studentRepositoty.findAllByStID(assistantApply.getStudentUsername());
                Map<String, Object> data = new HashMap<>();
                data.put("院系", student.getCollege());
                data.put("专业", student.getMajor());
                data.put("班级", student.getClasses());
                data.put("学号", student.getStID());
                data.put("姓名", student.getName());
                data.put("联系电话", student.getPhone());
                data.put("互选状态", typeMap.get(type));
                data.put("助教题目", projectName);
                datas.add(data);
            }
        }
        dynamicOperateExcelUtils.replaceCellValue(0, 0, college + grade + typeMap.get(type) + "助教助研学生互选统计表");
        if (!datas.isEmpty()) {
            dynamicOperateExcelUtils.appendRows(5, datas,
                    new String[]{"院系", "专业", "班级", "学号", "姓名", "联系电话", "互选状态",
                            "助教题目"});
        } else {
            dynamicOperateExcelUtils.replaceCellValue(5, 0, "无相关记录");
        }
        String newFileName = college + grade + typeMap.get(type) + "助教助研学生互选统计表.xlsx";
        dynamicOperateExcelUtils.exportExcel(new File(BASEPATH + newFileName));
        fileService.downloadFile(newFileName, request, response);
        fileService.deleteFile(BASEPATH + newFileName);
    }

    @Override
    public void getAssistantChoose(String college, String grade, String category, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        DynamicOperateExcelUtils dynamicOperateExcelUtils = new DynamicOperateExcelUtils(BASEPATH + "助教助研/" + "助教助研题目互选统计表模板.xlsx");
        List<Map<String, Object>> datas = new ArrayList<>();
        List<Assistant> assistants = assistantRepository.findAllByCollegeAndGradeAndCategory(college, grade, category);
        for (Assistant assistant : assistants) {
            Map<String, Object> data = new HashMap<>();
            data.put("题目名称", assistant.getName());
            data.put("教师", assistant.getTeacherUsername());
            data.put("所属院系", assistant.getCollege());
            data.put("所属系别", assistant.getDepartment());
            data.put("选择状态", assistant.getRecv());
            datas.add(data);
        }
        dynamicOperateExcelUtils.replaceCellValue(0, 0, college + grade + "助教助研题目互选统计表");
        if (!datas.isEmpty()) {
            dynamicOperateExcelUtils.appendRows(5, datas,
                    new String[]{"题目名称", "教师", "所属院系", "所属系别", "选择状态",});
        } else {
            dynamicOperateExcelUtils.replaceCellValue(5, 0, "无相关记录");
        }
        String newFileName = college + grade + "助教助研_题目互选统计表.xlsx";
        dynamicOperateExcelUtils.exportExcel(new File(BASEPATH + newFileName));
        fileService.downloadFile(newFileName, request, response);
        fileService.deleteFile(BASEPATH + newFileName);
    }

    @Override
    public void getAssistantArrange(String college, String major, String grade, String category, String sortMethod, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        DynamicOperateExcelUtils dynamicOperateExcelUtils = new DynamicOperateExcelUtils(BASEPATH + "助教助研/" + "助教助研安排表模板.xlsx");
        List<Map<String, Object>> datas = new ArrayList<>();
        List<StudentAssistant> studentAssistants = studentAssistantRepository.findAllByCollegeAndMajorAndGradeAndCategory(college, major, grade, category);
        if ("".equals(sortMethod)) {

        } else {

        }

        for (StudentAssistant studentAssistant : studentAssistants) {
            Map<String, Object> data = new HashMap<>();
            data.put("教师姓名", studentAssistant.getTeacherUsername());
            data.put("助教助研题目", studentAssistant.getProjectName());
            data.put("具体地点", assistantRepository.findById(studentAssistant.getProjectID()).orElse(null).getAddress());
            data.put("学生姓名", studentAssistant.getStudentName());
            data.put("联系方式（学生）", studentRepositoty.findAllByStID(studentAssistant.getStudentUsername()).getPhone());
            datas.add(data);
        }
        dynamicOperateExcelUtils.replaceCellValue(0, 0, "华中科技大学" + college + "--助教助研安排表");
        dynamicOperateExcelUtils.replaceCellValue(1, 0, "学院(系):" + college);
        dynamicOperateExcelUtils.replaceCellValue(1, 2, "专业(方向):" + major);
        if (!datas.isEmpty()) {
            dynamicOperateExcelUtils.appendRows(4, datas,
                    new String[]{"教师姓名", "助教助研题目", "具体地点", "学生姓名", "联系方式（学生）",});
        } else {
            dynamicOperateExcelUtils.replaceCellValue(4, 0, "无相关记录");
        }
        String newFileName = "华中科技大学" + college + major + "助教助研安排表.xlsx";
        dynamicOperateExcelUtils.exportExcel(new File(BASEPATH + newFileName));
        fileService.downloadFile(newFileName, request, response);
        fileService.deleteFile(BASEPATH + newFileName);
    }

    @Override
    public void getAssistantOffer(String college, String major, String grade, String category, String sortMethod, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        DynamicOperateExcelUtils dynamicOperateExcelUtils = new DynamicOperateExcelUtils(BASEPATH + "助教助研/" + "助教助研聘任表模板.xlsx");
        List<Map<String, Object>> datas = new ArrayList<>();
        List<StudentAssistant> studentAssistants = studentAssistantRepository.findAllByCollegeAndMajorAndGradeAndCategory(college, major, grade, category);
        if ("".equals(sortMethod)) {

        } else {

        }

        for (StudentAssistant studentAssistant : studentAssistants) {
            Student student = studentRepositoty.findAllByStID(studentAssistant.getStudentUsername());
            Assistant assistant = assistantRepository.findById(studentAssistant.getProjectID()).orElse(null);
            Map<String, Object> data = new HashMap<>();
            data.put("课题名称", studentAssistant.getProjectName());
            data.put("专业班级", assistant.getMajor());
            assert assistant != null;
            data.put("学时数", assistant.getHours());
            data.put("课堂头数", "");
            data.put("助教数", "");
            data.put("任课老师", studentAssistant.getTeacherUsername());
            data.put("助教学生", studentAssistant.getStudentName());
            data.put("学生学号", studentAssistant.getStudentUsername());
            data.put("联系方式", student.getPhone());
            data.put("每岗工作量", "");
            datas.add(data);
        }
        dynamicOperateExcelUtils.replaceCellValue(0, 0, "华中科技大学" + college + "--助教助研聘任表");
        dynamicOperateExcelUtils.replaceCellValue(1, 0, "学院(系):" + college);
        dynamicOperateExcelUtils.replaceCellValue(1, 2, "专业(方向):" + major);
        if (!datas.isEmpty()) {
            dynamicOperateExcelUtils.appendRows(4, datas,
                    new String[]{"课题名称", "专业班级", "学时数", "课堂头数", "助教数", "任课老师", "助教学生", "学生学号", "联系方式", "每岗工作量"});
        } else {
            dynamicOperateExcelUtils.replaceCellValue(4, 0, "无相关记录");
        }
        String newFileName = "华中科技大学" + college + major + "助教助研聘任表.xlsx";
        dynamicOperateExcelUtils.exportExcel(new File(BASEPATH + newFileName));
        fileService.downloadFile(newFileName, request, response);
        fileService.deleteFile(BASEPATH + newFileName);
    }


}
